//列表页的逻辑代码

//0 获取元素
const cateBox = document.querySelector('.category');
const box = document.querySelector('.box');
const filterBox = document.querySelector('.filter');
const saleTypeBox = document.querySelector('.saleType');
const sortBox = document.querySelector('.sort');
const select = document.querySelector('select');
const inp = document.querySelector('.searchBox > input');
const pageInfoBox = document.querySelector('.pageInfo');
const contentBox = document.querySelector('.content');

const abcc = datelist;


var current = 1
var pagesize = 16
var total = 1



getCategoryList()
function getCategoryList() {
  // 循环拼接字符串
  let str = '<li class="cate active">全部</li>'
  categoryy.forEach(item => {
    str += `<li class="cate">${ item }</li>`
  })

  // 1-4. 把 str 插入到 cateBox 内
  cateBox.innerHTML = str
}


//总页数
// let total = 10
//2-2 事件调整info内的信息
box.addEventListener('click',e=>{
    e = e || window.event;
    const target = e.target || e.srcElement;

    if(target.className==='cate'){
        for(var i = 0 ; i < cateBox.children.length ; i++){
            cateBox.children[i].classList.remove('active');
        }
        target.classList.add('active');
        const list_phone = datelist.filter(function(item){
            return item.category === "平板耳机";
        })
        datelist = list_phone;
        getGoodsList();
    }
    if(target.className === 'f'){
        for(var i = 0 ; i < filterBox.children.length ; i++){
            filterBox.children[i].classList.remove('active');
        }
        target.classList.add('active');
        const list_hot = datelist.filter(function(item){
            return item.is_hot === false;
        })
        datelist = list_hot;

        getGoodsList()
    }
   
    if(target.className === 's'){
        for(var i = 0 ; i < saleTypeBox.children.length ; i++){
            saleTypeBox.children[i].classList.remove('active')
        }
        target.classList.add('active')
        const list_hott = datelist.filter(function(item){
            return item.is_zhe === 8;
        })
        datelist = list_hott;
        getGoodsList();
    }
    if(target.className === 'sort2'){
        for(var i = 0;i < sortBox.children.length ; i++){
            sortBox.children[i].classList.remove('active');
        }
        target.classList.add('active');

        function compare(property){
            return function(value1,value2){
                let v1 = value1[property]

                let v2 = value2[property]

                return v1 - v2
            }
        }

        const abbb = datelist.sort(compare('jdPrice'))
        datelist = abbb
        getGoodsList()
    }
    if(target.className === 'prev'){
        if (current <= 1) return
        // 修改当前页
        current--
        // 从新调用 getGoodsList()
        getGoodsList()
    }
    if(target.className === 'next'){
        if (current >= total) return
        current++
        getGoodsList()
    }
})

select.addEventListener('change',()=>{
     // 5-1. 拿到 select 当前选中的内容, 赋值给 pagesize
     pagesize = select.value - 0
     // 5-2. 把当前页回归到 1
     current = 1
      // 5-3. 从新渲染页面
     getGoodsList()

})
inp.addEventListener('input',()=>{
    info.search = inp.value.trim();
    info.current =1 ;
    getGoodsList()

})







//3 请求列表数据
getGoodsList()
function getGoodsList(){
   
    var bind = datelist.slice((current - 1) * pagesize, current * pagesize)
    //渲染当前页信息
    // pageInfoBox.innerText = `${info.current} / ${total}`
    let str = ''
    bind.forEach(item =>{
        str +=`
            <li>
                <div class="show">
                    <img data-id="${item.id}" src="${item.image}" alt="">
                    <span class="hot ${item.is_hot ? 'active' : ''}"> HOT </span>
                    <span class="sale ${item.is_sale ? 'active' : ''}"> SALE </span>
                </div>
                <div class="info">
                    <p class="title">${item.name}</p>
                    <p>
                        折扣 : 0%
                    <p class="price">
                        <del class="old"> ￥ ${item.jdPrice} </del>
                        <span class="current"> ￥ ${item.jdPrice} </span>
                    </p>
                    <p>
                        <button data-id="${item.id}">加入购物车</button>
                    </p>
                </div>
            </li>
            `
    })
    contentBox.innerHTML = str;


    total = Math.ceil(datelist.length / pagesize)
    // 渲染 totalBox 标签
    pageInfoBox.innerHTML = current + ' / ' + total

    
}

contentBox.addEventListener('click', e =>{
    e = e || window.event;
    const target = e.target || e.srcElement;

    if(target.nodeName === 'IMG'){
        const id = target.dataset.id;
        window.sessionStorage.setItem('iid',id);

        window.location.href = './detail.html'
    }
    if(target.nodeName === 'BUTTON'){
        const login = window.localStorage.getItem('login');
        if(!login){
            window.localStorage.setItem('url','list');
            window.location.href = './login.html';
            return;
        }

        const id = window.localStorage.getItem('id');
        const goods_id = target.dataset.id - 0;
        // const token = window.localStorage.getItem('token');

        var goods = datelist.find(function(item){
            return item.id === goods_id;
        })
        var list1 = JSON.parse(window.localStorage.getItem('cart')) || [];
        if(!list1.length){
            goods.cart_number = 1
            list1.push(goods)
        }else{
            var res = list1.some(function(item) {return item.id === goods_id})
            if(res){
                var index = list1.findIndex(function(item){return item.id === goods_id})
                list1[index].cart_number++
            }else{
                goods.cart_number = 1
                list1.push(goods)
            }
            // setcookie('number',list1[index].cart_number,3600)

        }
        window.localStorage.setItem('cart',JSON.stringify(list1))
        if(!id){
            window.localStorage.setItem('url','list');
            window.location.href = './login.html';
            return;
        }
        alert('加入购物车成功')
    }
})





